package com.lyandwc.lw_bbs.controller;

import com.alibaba.fastjson.JSONObject;
import com.lyandwc.lw_bbs.entity.User;
import com.lyandwc.lw_bbs.security.entity.Role;
import com.lyandwc.lw_bbs.security.entity.UserAuthDetails;
import com.lyandwc.lw_bbs.service.UserService;
import com.lyandwc.lw_bbs.utils.ResponseUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/users")
public class UserController {
    private UserService userService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public UserController(UserService userService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.userService = userService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN', 'USER')")
    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public JSONObject getInfo(
            Authentication authentication
    ) {
        int userId = (int) authentication.getCredentials();
        User user = userService.getById(userId);
        return ResponseUtils.success(user);
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN', 'USER')")
    @RequestMapping(value = "/info/{uid}", method = RequestMethod.GET)
    public JSONObject getInfo(
            @PathVariable int uid
    ) {
        User user = userService.getById(uid);
        if (user != null) {
            return ResponseUtils.success(user);
        } else {
            return ResponseUtils.success("No such user.");
        }
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN', 'USER')")
    @RequestMapping(value = "/info", method = RequestMethod.PUT)
    public JSONObject updateInfo(
            Authentication authentication,
            @RequestBody Map<String, String> map
    ) {
        int userId = (int) authentication.getCredentials();
        User user = userService.getById(userId);

        String email = map.get("email");
        String bio = map.get("bio");
        String avatar = map.get("avatar");

        if (email != null) {
            user.setEmail(email);
        }
        if (bio != null) {
            user.setBio(bio);
        }
        if (avatar != null) {
            user.setAvatar(avatar);
        }

        userService.updateById(user);

        return ResponseUtils.success(user);
    }

    @PreAuthorize(value = "hasAnyRole('ADMIN', 'USER')")
    @RequestMapping(value = "/auth", method = RequestMethod.PUT)
    public JSONObject updateAuth(
            Authentication authentication,
            @RequestBody Map<String, String> map
    ) {
        UserAuthDetails userAuthDetails = (UserAuthDetails) authentication.getPrincipal();
        User user = userService.getById(userAuthDetails.getId());
        String password = map.get("password");
        String newPassword = map.get("newPassword");
        if (user != null && password != null && newPassword != null
                && bCryptPasswordEncoder.matches(password, user.getPassword())
        ) {
            user.setPassword(bCryptPasswordEncoder.encode(password));
            userService.updateById(user);
            return ResponseUtils.success(user);
        }
        return ResponseUtils.fail("Illegal format params.");
    }
}
